package live.ifox.stage;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import live.ifox.base.BaseRestActivity;
import live.ifox.factory.Entry;
import live.ifox.factory.ID;
import live.ifox.helper.AdapterHelper;
import live.ifox.helper.CommonHelper;

public class StageViewActivity extends BaseRestActivity {
    boolean isNormal;
    ListView listView;
    SwipeRefreshLayout swipeLayout;
    JSONArray array;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stage_view);

        isNormal = true;

        listView = findViewById(R.id.listView);
        registerForContextMenu(listView);

        swipeLayout = findViewById(R.id.swipeLayout);

        entry = getIntent().getStringExtra("entry");
        baseUrl = getIntent().getStringExtra("baseUrl");
        if (entry.isEmpty() || baseUrl.isEmpty()) {
            isNormal = false;
            CommonHelper.showMessage(this, "缺少参数！");
        } else {
            setWindowTitle();
            swipeLayout.setOnRefreshListener(() -> {
                swipeLayout.setRefreshing(false);
                updateView();
            });
            updateView();
        }
    }

    void setWindowTitle() {
        switch (entry) {
            case Entry.AssembleLog:
                actionBar.setTitle(R.string.assemble_log);
                break;
            case Entry.Parlor:
                actionBar.setTitle(R.string.parlor);
                break;
            case Entry.Journal:
                actionBar.setTitle(R.string.journal);
                break;
            case Entry.Schedule:
                actionBar.setTitle(R.string.schedule);
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, ID.ACTION_ADD, 0, "添加...");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case ID.ACTION_ADD:
                switch (entry) {
                    case Entry.Parlor:
                        startActivityForResult(new Intent(this,
                                        ParlorEditor.class),
                                ID.PARLOR_EDITOR);
                        return true;
                    case Entry.Journal:
                        startActivityForResult(new Intent(this,
                                        JournalEditor.class),
                                ID.JOURNAL_EDITOR);
                        return true;
                    case Entry.AssembleLog:
                        startActivityForResult(new Intent(this,
                                        AssembleLogEditor.class),
                                ID.ASSEMBLE_LOG_EDITOR);
                        return true;
                    default:
                        return false;
                }
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        // getMenuInflater().inflate(R.menu.operate_menu, menu);
        menu.add(0, ID.ACTION_COPY, 0, "复制");
        menu.add(0, ID.ACTION_EDIT, 1, "编辑...");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (array.isEmpty())
            return false;

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        JSONObject object = array.getJSONObject(position);
        if (object.isEmpty())
            return false;

        switch (item.getItemId()) {
            case ID.ACTION_COPY: {
                switch (entry) {
                    case Entry.Parlor:
                        return do_copyItem(object);
                    case Entry.Journal:
                        return do_copyItem(object);
                    case Entry.Schedule:
                        return do_copyItem(object);
                    default:
                        return false;
                }
            }
            case ID.ACTION_EDIT:
                switch (entry) {
                    case Entry.Parlor:
                        return parlor_edit(object);
                    case Entry.Journal:
                        return journal_edit(object);
                    case Entry.Schedule:
                        return journal_edit(object);
                    case Entry.AssembleLog:
                        return assembleLog_edit(object);
                    default:
                        return false;
                }
        }
        return super.onContextItemSelected(item);
    }

    boolean do_copyItem(JSONObject object) {
        String detail = object.getString("detail");
        if (detail == null || detail.isEmpty())
            return false;

        CommonHelper.setClipboardText(this, entry, detail);
        CommonHelper.showMessage(this, "已复制到剪贴板");
        return true;
    }

    public void updateView() {
            httpGet(baseUrl + "get_detail");
    }

    void processJournal() {
        SimpleAdapter adapter = AdapterHelper.getTableAdapter(this,
                array, new String[]{"category", "detail"});
        listView.setAdapter(adapter);
    }

    void processParlor() {
        SimpleAdapter adapter = AdapterHelper.getTableAdapter(this,
                array, new String[]{"category", "detail"});
        listView.setAdapter(adapter);
    }

    void processAssembleLog() {
        List<Map<String, Object>> model = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = array.getJSONObject(i);
            Map<String, Object> item = new HashMap<>();
            item.put("date_", object.getString("date_"));
            String detail = object.getString("provider") + "  " +
                    object.getString("name") + "  " +
                    object.getInteger("number") + "  " +
                    object.getString("remark");
            item.put("detail", detail);
            model.add(item);
        }
        if (!model.isEmpty()) {
            SimpleAdapter adapter = AdapterHelper.getTableAdapter(this,
                    model, new String[]{"date_", "detail"});
            listView.setAdapter(adapter);
        }
    }

    void processSchedule() {
        SimpleAdapter adapter = AdapterHelper.getTableAdapter(this,
                array, new String[]{"date_", "detail"});
        listView.setAdapter(adapter);

        /* // 长按复制到剪贴板
        listView.setOnItemLongClickListener(
                (parent, view, position, id) -> {
                    String date_ = array.getJSONObject(position).getString("date_");
                    String detail = array.getJSONObject(position).getString("detail");
                    CommonHelper.setClipboardText(this, date_, detail);
                    CommonHelper.showMessage(this, "已复制到剪贴板");
                    return true;
                }
        );
        */
    }

    boolean journal_edit(JSONObject object) {
        int id = object.getIntValue("id");
        String category = object.getString("category");
        String detail = object.getString("detail");
        if (id == 0 || category.isEmpty() || detail.isEmpty())
            return false;

        Intent intent = new Intent(this, JournalEditor.class);
        intent.putExtra("id", id);
        intent.putExtra("category", category);
        intent.putExtra("detail", detail);
        startActivityForResult(intent, ID.JOURNAL_EDITOR);
        return true;
    }

    boolean parlor_edit(JSONObject object) {
        int id = object.getIntValue("id");
        String category = object.getString("category");
        String detail = object.getString("detail");
        if (id == 0 || category.isEmpty() || detail.isEmpty())
            return false;

        Intent intent = new Intent(this, ParlorEditor.class);
        intent.putExtra("id", id);
        intent.putExtra("category", category);
        intent.putExtra("detail", detail);
        startActivityForResult(intent, ID.PARLOR_EDITOR);
        return true;
    }

    boolean assembleLog_edit(JSONObject object) {
        int id = object.getIntValue("id");
        String provider = object.getString("provider");
        String name = object.getString("name");
        int number = object.getIntValue("number");
        String remark = object.getString("remark");
        if (id == 0 || provider.isEmpty() ||
                name.isEmpty() || number == 0)
            return false;

        Intent intent = new Intent(this, AssembleLogEditor.class);
        intent.putExtra("id", id);
        intent.putExtra("provider", provider);
        intent.putExtra("name", name);
        intent.putExtra("number", number);
        intent.putExtra("remark", remark);
        startActivityForResult(intent, ID.ASSEMBLE_LOG_EDITOR);
        return true;
    }

    @Override
    public void processReply(JSONObject rootObject) {
        array = AdapterHelper.verifyObject(rootObject, entry);
        if (array.isEmpty()) {
            listView.setAdapter(null);
            return;
        }

        switch (entry) {
            case Entry.Parlor:
                processParlor();
                break;
            case Entry.Journal:
                processJournal();
                break;
            case Entry.AssembleLog:
                processAssembleLog();
                break;
            case Entry.Schedule:
                processSchedule();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ID.RESULT_DONE) {
            updateView();
        }
    }
}